package com.hclc.controller;

import cn.hutool.core.util.ReUtil;
import com.hclc.config.util.AssertUtil;
import com.hclc.entity.model.contans.ApiConst;
import com.hclc.entity.model.result.ResultEntity;
import com.hclc.util.sftp.SftpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author: hef
 * 文件相关controller
 * @Date: Create in 17:04 2019-10-22
 */
@Api(tags = "1.0-file", description = "公用-文件")
@RestController
@RequestMapping("/commons/file")
@Slf4j
public class CommonsFileController {

    /**
     * 上传图片
     *
     * @param file
     * @return com.hclc.result.ResultEntity<java.lang.String>
     * @author hef
     * @version 1.0
     * @date 2019-10-22 17:18
     */
    @ApiOperation("上传图片")
    @PostMapping(value = "/uploadPicture")
    public ResultEntity<String> uploadPicture(@ApiParam(value = "文件", required = true) @RequestBody MultipartFile file) throws IOException {
        boolean contains = ReUtil.contains(ApiConst.IMG_REG, file.getOriginalFilename());
        AssertUtil.isTrue(contains, () -> "图片格式不正确");
        // 创建上传器
        SftpUtil builder = SftpUtil.builder();
        String url = builder.uploadFile(file.getOriginalFilename(), file);
        if (StringUtils.isNotBlank(url)) {
            return ResultEntity.ResultSuccess(url);
        }
        return ResultEntity.ResultFail(ApiConst.CODE_FAIL, "上传失败");
    }


    /**
     * 上传文件
     *
     * @param file
     * @return com.hclc.result.ResultEntity<java.lang.String>
     * @author hef
     * @version 1.0
     * @date 2019-10-22 17:18
     */
    @ApiOperation("上传文件")
    @PostMapping(value = "/uploadFile")
    public ResultEntity<String> uploadFile(@ApiParam(value = "文件", required = true) @RequestBody MultipartFile file) throws IOException {
        // 创建上传器
        SftpUtil builder = SftpUtil.builder();
        String url = builder.uploadFile(file.getOriginalFilename(), file);
        if (StringUtils.isNotBlank(url)) {
            return ResultEntity.ResultSuccess(url);
        }
        return ResultEntity.ResultFail(ApiConst.CODE_FAIL, "上传失败");
    }
}
